package com.halden.mycache.support.saveStrategy.RDBSaveStrategy.impl;

import com.halden.mycache.support.listener.impl.LogCacheRemoveListener;
import com.halden.mycache.support.saveStrategy.RDBSaveStrategy.IRDBSaveMode;
import com.halden.mycache.support.saveStrategy.RDBSaveStrategy.IRDBSaveStrategy;
import com.halden.mycache.core.IMyCache;
import com.halden.mycache.core.Impl.CacheValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: halden
 * @Data:2023/2/5 9:36
 * @Description: 使用RDB模式进行持久化
 * @since 0.0.3
 */
public class RDBSaveStrategy<K,V> implements IRDBSaveStrategy<K,V> {

    private static Logger logger = LogManager.getLogger(RDBSaveStrategy.class);

    /**
     * 保存模式
     */
    private IRDBSaveMode<K,V> saveMode;

    /**
     * 线程执行类
     * @since 0.0.3
     */
    private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();

    /**
     * 每十分钟进行一次持久化
     * @param myCache
     * @param fileName
     */
    @Override
    public void startStrategy(IMyCache<K, V> myCache, String fileName) {
        EXECUTOR_SERVICE.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                saveMode.save(myCache,fileName);
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    @Override
    public void close(IMyCache<K, V> myCache, String fileName) {
        // 关闭线程池
        EXECUTOR_SERVICE.shutdown();
        // 最后执行一次持久化
        saveMode.save(myCache,fileName);
        logger.info("rdb close successfully");
    }

    @Override
    public Map<K, CacheValue<V>> readSave(File file, Map<K,CacheValue<V>> map) {
        return saveMode.readSave(file, map);
    }

    @Override
    public void setSaveMode(IRDBSaveMode<K, V> saveMode) {
        this.saveMode = saveMode;
    }

}
